document.addEventListener('DOMContentLoaded', function() {
    const gallery = document.getElementById('image-gallery');
    const modal = document.getElementById('modal');
    const modalImg = document.getElementById('modal-image');
    const closeBtn = document.querySelector('.close');
    const prevBtn = document.createElement('button');
    const nextBtn = document.createElement('button');

    // LOGO按钮和导航栏元素
    const logoBtn = document.getElementById('logo-btn');
    const sideNav = document.getElementById('side-nav');
    const navList = document.getElementById('nav-list');

    // 默认配置
    const CONFIG = {
        preload_count: 10
    };

    // 当前图像索引和图像数组
    let currentImages = [];
    let currentIndex = 0;

    // 图像缩放相关变量
    let scale = 1;
    let minScale = 0.5;
    let maxScale = 3;
    let isDragging = false;
    let startX, startY, startTranslateX, startTranslateY;
    let translateX = 0;
    let translateY = 0;
    let startTouchDistance = 0;

    // 根据文件夹加载图片的函数
    function loadImagesByFolder(folderName) {
        // 关闭导航栏
        if (sideNav) {
            sideNav.classList.remove('active');
        }

        // 显示加载提示
        gallery.innerHTML = '<div class="loading">加载中...</div>';

        // 构造API请求URL
        let apiUrl = '/api/images';
        if (folderName && folderName !== '/') {
            // 如果指定了文件夹，则添加查询参数
            apiUrl += '?folder=' + encodeURIComponent(folderName);
        }

        // 获取指定文件夹下的图像数据
        fetch(apiUrl)
            .then(response => response.json())
            .then(images => {
                currentImages = images;
                // 清空加载提示
                gallery.innerHTML = '';

                if (images.length === 0) {
                    gallery.innerHTML = '<div class="no-images">该文件夹下未找到图像文件</div>';
                    return;
                }

                // 为每个图像创建缩略图
                images.forEach((image, index) => {
                    const thumbnail = document.createElement('div');
                    thumbnail.className = 'thumbnail';

                    // 创建图像元素
                    const img = document.createElement('img');
                    // 根据图像类型生成正确的URL
                    if (image.type === 'remote') {
                        // 远程图像
                        img.src = `/api/image/${encodeURIComponent(image.path)}?server=${encodeURIComponent(image.server)}`;
                    } else {
                        // 本地图像
                        img.src = `/api/image/${encodeURIComponent(image.path)}`;
                    }
                    img.alt = image.name;
                    img.loading = 'lazy'; // 懒加载

                    // 预加载优化
                    if (index < CONFIG.preload_count) {
                        img.loading = 'eager';
                    }

                    // 创建图像信息
                    const info = document.createElement('div');
                    info.className = 'image-info';

                    // 只显示文件名，且只显示为一行
                    const fileName = document.createElement('p');
                    fileName.textContent = image.name;
                    info.appendChild(fileName);

                    thumbnail.appendChild(img);
                    thumbnail.appendChild(info);

                    // 添加点击事件以打开模态框
                    thumbnail.addEventListener('click', function() {
                        openModal(index);
                    });

                    gallery.appendChild(thumbnail);
                });
            })
            .catch(error => {
                console.error('Error loading images:', error);
                gallery.innerHTML = '<div class="no-images">加载图像时出错</div>';
            });
    }

    // 创建导航按钮
    prevBtn.innerHTML = '&#10094;'; // 左箭头
    prevBtn.className = 'nav-btn prev-btn';
    nextBtn.innerHTML = '&#10095;'; // 右箭头
    nextBtn.className = 'nav-btn next-btn';

    modal.appendChild(prevBtn);
    modal.appendChild(nextBtn);

    // LOGO按钮点击事件
    if (logoBtn && sideNav) {
        logoBtn.addEventListener('click', function() {
            sideNav.classList.toggle('active');
        });
    }

    // 获取文件夹列表并显示在导航栏中
    if (navList) {
        fetch('/api/folders')
            .then(response => response.json())
            .then(folders => {
                // 清空加载提示
                navList.innerHTML = '';

                if (folders.length === 0) {
                    const li = document.createElement('li');
                    li.textContent = '未找到图像文件夹';
                    li.classList.add('no-folders');
                    navList.appendChild(li);
                    return;
                }

                // 为每个文件夹创建列表项
                folders.forEach(folder => {
                    const li = document.createElement('li');
                    li.textContent = folder;
                    li.dataset.folder = folder; // 存储文件夹名称用于后续操作

                    // 添加点击事件
                    li.addEventListener('click', function() {
                        loadImagesByFolder(folder);
                    });

                    navList.appendChild(li);
                });
            })
            .catch(error => {
                console.error('Error loading folders:', error);
                navList.innerHTML = '<li class="loading">加载文件夹时出错</li>';
            });
    }

    // 页面加载时默认只显示根目录下的图像
    loadImagesByFolder('/');

    // 打开模态框函数
    function openModal(index) {
        currentIndex = index;
        const image = currentImages[index];

        // 重置缩放和位置
        resetZoom();

        // 根据图像类型生成正确的URL
        if (image.type === 'remote') {
            // 远程图像
            modalImg.src = `/api/image/${encodeURIComponent(image.path)}?server=${encodeURIComponent(image.server)}`;
        } else {
            // 本地图像
            modalImg.src = `/api/image/${encodeURIComponent(image.path)}`;
        }

        modal.style.display = 'block';
        updateNavigationButtons();
    }

    // 重置图像缩放
    function resetZoom() {
        scale = 1;
        translateX = 0;
        translateY = 0;
        // 不要直接设置transform样式，而是让CSS处理居中定位
        modalImg.style.transform = '';
    }

    // 更新图像变换
    function updateImageTransform() {
        // 保留CSS的居中定位，只添加缩放和平移
        modalImg.style.transform = `translate(-50%, -50%) scale(${scale}) translate(${translateX}px, ${translateY}px)`;
    }

    // 更新导航按钮状态
    function updateNavigationButtons() {
        prevBtn.style.display = currentIndex > 0 ? 'block' : 'none';
        nextBtn.style.display = currentIndex < currentImages.length - 1 ? 'block' : 'none';
    }

    // 切换到上一张图像
    function showPrevImage() {
        if (currentIndex > 0) {
            openModal(currentIndex - 1);
        }
    }

    // 切换到下一张图像
    function showNextImage() {
        if (currentIndex < currentImages.length - 1) {
            openModal(currentIndex + 1);
        }
    }

    // 关闭模态框
    closeBtn.addEventListener('click', function() {
        modal.style.display = 'none';
    });

    // 点击模态框背景关闭
    modal.addEventListener('click', function(event) {
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    });

    // 导航按钮事件
    prevBtn.addEventListener('click', function(event) {
        event.stopPropagation();
        showPrevImage();
    });

    nextBtn.addEventListener('click', function(event) {
        event.stopPropagation();
        showNextImage();
    });

    // ESC键关闭模态框
    document.addEventListener('keydown', function(event) {
        if (modal.style.display === 'block') {
            switch(event.key) {
                case 'Escape':
                    modal.style.display = 'none';
                    break;
                case 'ArrowLeft':
                    showPrevImage();
                    break;
                case 'ArrowRight':
                    showNextImage();
                    break;
                case '+':
                case '=':
                    // 放大
                    zoom(0.2);
                    break;
                case '-':
                    // 缩小
                    zoom(-0.2);
                    break;
                case '0':
                    // 重置缩放
                    resetZoom();
                    break;
            }
        }
    });

    // 触摸手势支持
    let touchStartX = 0;
    let touchEndX = 0;

    // 鼠标事件处理
    modalImg.addEventListener('mousedown', function(event) {
        if (scale > 1) {
            isDragging = true;
            startX = event.clientX;
            startY = event.clientY;
            startTranslateX = translateX;
            startTranslateY = translateY;
            modalImg.style.cursor = 'grabbing';
            event.preventDefault();
        }
    });

    document.addEventListener('mousemove', function(event) {
        if (isDragging) {
            const dx = event.clientX - startX;
            const dy = event.clientY - startY;
            translateX = startTranslateX + dx;
            translateY = startTranslateY + dy;
            updateImageTransform();
        }
    });

    document.addEventListener('mouseup', function() {
        isDragging = false;
        modalImg.style.cursor = 'grab';
    });

    // 滚轮缩放
    modalImg.addEventListener('wheel', function(event) {
        event.preventDefault();
        const delta = event.deltaY > 0 ? -0.1 : 0.1;
        zoomAtPoint(delta, event.clientX, event.clientY);
    });

    // 触摸事件处理
    modalImg.addEventListener('touchstart', function(event) {
        touchStartX = event.changedTouches[0].screenX;

        if (event.touches.length === 2) {
            // 双指触摸开始
            startTouchDistance = getTouchDistance(event.touches[0], event.touches[1]);
        } else if (scale > 1 && event.touches.length === 1) {
            // 单指触摸拖拽
            isDragging = true;
            startX = event.touches[0].clientX;
            startY = event.touches[0].clientY;
            startTranslateX = translateX;
            startTranslateY = translateY;
        }
    }, false);

    modalImg.addEventListener('touchmove', function(event) {
        event.preventDefault();

        if (event.touches.length === 2) {
            // 双指缩放
            const currentDistance = getTouchDistance(event.touches[0], event.touches[1]);
            const delta = (currentDistance - startTouchDistance) / 100;
            zoom(delta * 0.1);
            startTouchDistance = currentDistance;
        } else if (isDragging && event.touches.length === 1) {
            // 单指拖拽
            const dx = event.touches[0].clientX - startX;
            const dy = event.touches[0].clientY - startY;
            translateX = startTranslateX + dx;
            translateY = startTranslateY + dy;
            updateImageTransform();
        }
    }, false);

    modalImg.addEventListener('touchend', function(event) {
        isDragging = false;

        if (event.changedTouches.length > 0) {
            touchEndX = event.changedTouches[0].screenX;
            handleSwipe();
        }
    }, false);

    // 计算两指间距离
    function getTouchDistance(touch1, touch2) {
        const dx = touch1.clientX - touch2.clientX;
        const dy = touch1.clientY - touch2.clientY;
        return Math.sqrt(dx * dx + dy * dy);
    }

    // 处理滑动切换
    function handleSwipe() {
        const swipeThreshold = 50; // 最小滑动距离

        if (scale <= 1) { // 只有在未缩放时才允许滑动切换
            if (touchStartX - touchEndX > swipeThreshold) {
                // 向左滑动，显示下一张图像
                showNextImage();
            } else if (touchEndX - touchStartX > swipeThreshold) {
                // 向右滑动，显示上一张图像
                showPrevImage();
            }
        }
    }

    // 缩放函数
    function zoom(delta) {
        const newScale = scale + delta;
        if (newScale >= minScale && newScale <= maxScale) {
            scale = newScale;
            updateImageTransform();
        }
    }

    // 在指定点缩放
    function zoomAtPoint(delta, clientX, clientY) {
        const rect = modalImg.getBoundingClientRect();
        const x = clientX - rect.left;
        const y = clientY - rect.top;

        const newScale = Math.max(minScale, Math.min(maxScale, scale + delta));
        const scaleRatio = newScale / scale;

        scale = newScale;
        translateX = x - (x - translateX) * scaleRatio;
        translateY = y - (y - translateY) * scaleRatio;

        updateImageTransform();
    }
});